package gr.handmademarket.ui.panels;

import gr.handmademarket.po.enums.Role;
import gr.handmademarket.po.implementations.Buyer;
import gr.handmademarket.po.implementations.Seller;
import gr.handmademarket.po.interfaces.User;

import java.util.ArrayList;
import java.util.Arrays;

import org.apache.wicket.ajax.AjaxRequestTarget;
import org.apache.wicket.ajax.form.AjaxFormComponentUpdatingBehavior;
import org.apache.wicket.markup.html.form.DropDownChoice;
import org.apache.wicket.markup.html.form.Form;
import org.apache.wicket.markup.html.panel.EmptyPanel;
import org.apache.wicket.markup.html.panel.FeedbackPanel;
import org.apache.wicket.markup.html.panel.Panel;
import org.apache.wicket.model.CompoundPropertyModel;
import org.apache.wicket.model.IModel;
import org.apache.wicket.model.Model;


/**
 * page for creating an account.
 */
public class RegisterPanel 
extends Panel{

	/**
	 * serialVersionUID
	 */
	private static final long serialVersionUID = 1L;

	/**
	 * the form containing the user type combo.
	 */
	@SuppressWarnings("nls")
	private Form<Role> form = new Form<Role>("tform");
	
	/**
	 * file upload field.
	 */
	@SuppressWarnings("nls")
	private DropDownChoice<Role> typesCombo = 
		new DropDownChoice<Role>("typesCombo", new Model<Role>(), 
				new ArrayList<Role>(Arrays.asList(Role.values())));
	
	/**
	 * the user panel.
	 */
	@SuppressWarnings("nls")
	private Panel userPanel = new EmptyPanel("userPanel");
	
	/**
	 * the feedback panel.
	 */
	@SuppressWarnings("nls")
	private FeedbackPanel feedbackPanel = new FeedbackPanel("feedbackPanel");
	
	/**
	 * sub item combo updating behavior.
	 */
	@SuppressWarnings("nls")
	private AjaxFormComponentUpdatingBehavior behavior = new AjaxFormComponentUpdatingBehavior("onChange") { 
		/**
    	 *UID.
    	 */
    	private static final long serialVersionUID = 1L;

    	@Override
    	protected void onUpdate(AjaxRequestTarget target) {
    		if (typesCombo.getModelObject() == null){
    			return;
    		}
    		User user = typesCombo.getModelObject().equals(Role.BUYER)?new Buyer() : new Seller();
    		IModel<User> model = new CompoundPropertyModel<User>(user);
    		BuyerPanel newPanel = new BuyerPanel("userPanel", model);
    		newPanel.setOutputMarkupId(true);
    		newPanel.setOutputMarkupPlaceholderTag(true);
    		RegisterPanel.this.get("userPanel").replaceWith(newPanel);
    		userPanel = newPanel;
    		target.add(userPanel);
    	}
	};
	
	/**
	 * Creates a new RegisterPanel object. 
	 * @param id 
	 *
	 */
	public RegisterPanel(String id){
		super(id);
		add(form);
		form.add(typesCombo);
		add(userPanel);
		userPanel.setOutputMarkupId(true);
		userPanel.setOutputMarkupPlaceholderTag(true);
		typesCombo.add(behavior);
		add(feedbackPanel.setOutputMarkupId(true));
	}
	
}
